package com.mlnx.service.common.utils;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * Created by amanda.shan on 2017/11/30.
 */
public class XmlUtils {

    public static String toXml(Object o) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(o.getClass());
        Marshaller marshaller = context.createMarshaller();

        StringWriter sw = new StringWriter();
        marshaller.marshal(o, sw);

        return sw.toString();
    }

    public static <T> T toObj(Class c, String xml) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(c);
        Unmarshaller u = jc.createUnmarshaller();
        StringReader stringReader = new StringReader(xml);
        T t = (T) u.unmarshal(stringReader);
        return t;
    }
}
